package com.xiao.sulinges.service.imp;

import com.alibaba.fastjson.JSON;
import com.xiao.sulinges.service.ProductEsService;
import com.xiao.sulinges.vo.CommodityVo;
import com.xiao.sulingpublic.to.ClassifyEsTo;
import com.xiao.sulingpublic.utils.R;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 1322127758@qq.com
 * @date: 2022/3/20 10:45
 * @作用:
 */
@Service("productEsService")
public class ProductEsServiceImpl implements ProductEsService {
    private static final String index = "suling";
    /**
     * 操作es用的
     */
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void save(CommodityVo commodityVo) throws IOException {
        //1.创建IndexRequest对象，要保存到的索引 xiao
        IndexRequest indexRequest = new IndexRequest(index);
        //2.数据的id
        indexRequest.id(String.valueOf(commodityVo.getCoId()));
        //3.将要存储的数据转化为JSON数据,添加到IndexRequest对象中
        String s = JSON.toJSONString(commodityVo);
        indexRequest.source(s, XContentType.JSON);

        //4.保存数据到索引
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }


    /**
     * 删除指定id的数据
     * @param coId
     * @return
     */
    @Override
    public R delete(Long coId) throws IOException {
        //1.创建IndexRequest对象，要保存到的索引 xiao
        DeleteRequest deleteRequest = new DeleteRequest(index);
        //2.删除
        deleteRequest.id(String.valueOf(coId));
        //4.保存数据到索引
        restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return R.ok();
    }

    /**
     * 修改数据
     */
    @Override
    public R update(CommodityVo commodityVo) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest();
        //1.创建IndexRequest对象，要保存到的索引 xiao
        IndexRequest indexRequest = new IndexRequest(index);
        //2.数据的id
        indexRequest.id(String.valueOf(commodityVo.getCoId()));
        //3.将要存储的数据转化为JSON数据,添加到IndexRequest对象中
        String s = JSON.toJSONString(commodityVo);
        indexRequest.source(s, XContentType.JSON);

        updateRequest.doc(indexRequest);

        restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
        return R.ok();
    }

    @Override
    public List<CommodityVo> list(ClassifyEsTo classifyEsTo) throws IOException {

        //用于构建DSL语句
        SearchSourceBuilder searchSource = new SearchSourceBuilder();

        if(null != classifyEsTo){
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            boolQuery.must(QueryBuilders.matchQuery("coMemberUsername",classifyEsTo.getCoMemberUsername()));

            if(classifyEsTo.getClId() != null){
                boolQuery.must(QueryBuilders.matchQuery("clId",classifyEsTo.getClId()));
            }else if(classifyEsTo.getClName() != null && !"".equals(classifyEsTo.getClName())){
                boolQuery.must(QueryBuilders.matchQuery("clName",classifyEsTo.getClName()));
            }

            searchSource.query(boolQuery);
        }

        searchSource.sort("clId", SortOrder.ASC);

        SearchRequest searchRequest = new SearchRequest(new String[]{index}, searchSource);

        //执行检索条件
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //封装查询到的数据返回
        long value = search.getHits().getTotalHits().value;
        if(value == 0){
            //查询到0跳数据
            return null;
        }

        List<CommodityVo> commodityVos = new ArrayList<>();
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            //获取到内容数据
            String sourceAsString = hit.getSourceAsString();
            //将字符串转换为我们自己的对象
            CommodityVo commodityVo = JSON.parseObject(sourceAsString, CommodityVo.class);
            commodityVos.add(commodityVo);
        }

        return commodityVos;
    }
}
